<?php

class Profil extends BaseProfil
{
    public function __toString()
    {
        return $this->getPrezime().' '.$this->getIme();
    }

    public function save(PropelPDO $con = null)
    {
      $this->setIme(trim($this->getIme()));
      $this->setPrezime(trim($this->getPrezime()));

      // Novi profil
      if(!$this->getId())
      {
        // postavi hash passworda
        if(!$this->getPlainPassword())
          $this->setPlainPassword(ProfilPeer::createRandomPassword());
        $this->setPassword(md5($this->getPlainPassword()));
        if(!$this->getUsername())
          $this->setUsername(ProfilPeer::defaultUsername($this));

        if($this->getEMail() == '' and in_array($this->getTip(), array(ProfilPeer::$tip['administrator'], ProfilPeer::$tip['upravnik'], ProfilPeer::$tip['profesor'], ProfilPeer::$tip['menadzer'], ProfilPeer::$tip['operater'])))
        {
          $this->setEMail($this->getUsername().'@'.Functions::$domen);
          if(!Functions::newEmail($this->getEMail(), $this->getPlainPassword()))
            return 0;
        }

      }

      // Edit starog
      else
      {
        if($this->getPlainPassword() != '')
          $this->setPassword(md5($this->getPlainPassword()));

        // Promena maila iz naseg u nas ili neki drugi
        if(Functions::nasEmail($this->getId()))
        {
          if($this->isColumnModified('profil.E_MAIL'))
            if(!Functions::deleteEmail($this->getId()))
              return 0;

          if(strstr($this->getEMail(), Functions::$domen))
            if(!Functions::newEmail($this->getEMail(), $this->getPlainPassword()))
              return 0;
        }

        // Promena maila iz nekog drugog u nas
        else if(strstr($this->getEMail(), Functions::$domen))
          if(!Functions::newEmail($this->getEMail(), $this->getPlainPassword()))
            return 0;
      }

      parent::save();

      return 1;
    }

    public function delete(PropelPDO $con = null)
    {
       if(strstr($this->getEMail(), Functions::$domen))
         Functions::deleteEmail($this->getId());

       parent::delete();
    }
}